package com.yc.proxy;



import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Title: cglib 代理工厂类 <br>
 * Description: <br>
 * Author:陈圆(chenyuan@bosssoft.com.cn) <br>
 * Date:2020/9/14
 */
public class EnhancerFactory {

    private Object targetObject;

    public EnhancerFactory(Object targetObject) {
        this.targetObject = targetObject;
    }

    public Object createEnhancer() {
        // 创建Enhancer对象
        Enhancer en = new Enhancer();
        // cglib创建代理对象，对目标对象创建子类对象
        en.setSuperclass(targetObject.getClass());
        MethodInterceptor m = new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("开启");
                Object o1 = methodProxy.invokeSuper(o, objects);
                System.out.println("结束");
                return o1;
            }
        };
        en.setCallback(m); // 代理需要做的事请
        Object o = en.create(); // 创建代理
        return o;

    }
}
